package com.yuhuihui.common.utils.encryption;

import com.yuhuihui.common.utils.CharsetUtil;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.ObjectUtils;

import javax.crypto.Cipher;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESedeKeySpec;
import javax.crypto.spec.IvParameterSpec;
import java.nio.charset.Charset;
import java.security.Key;
import java.security.Security;


/**
 * 3DES工具类
 *
 * @author yuhh
 * @date 2023-05-25 14:47:52
 */
public final class TripleDesUtil {

    /** logger */
    private static final Logger logger = LoggerFactory.getLogger(TripleDesUtil.class);
    /**
     * 偏移变量，ECB模式不需要
     */
    private final static String IV_PARAMETER = null;
    /**
     * 密钥算法
     */
    private final static String ALGORITHM = "DESede";
    /**
     * 加密/解密算法-工作模式-填充模式
     */
    private final static String CIPHER_ALGORITHM = "DESede/ECB/PKCS7Padding";
    /**
     * 默认编码
     */
    private final static Charset CHARSET = CharsetUtil.CHARSET_UTF_8;

    /** key的最小值 */
    private final static  int KEY_MIN_LENGTH = 8;

    static {
        Security.addProvider(new BouncyCastleProvider());
    }

    /**
     * 3DES加密字符串--base64加密
     *
     * @param password  解密密码，长度不能够小于8位
     * @param appSecret 偏移变量
     * @param data      待加密字符串
     * @return {@link String } 加密后内容
     * @author yuhh
     * @date 2023-05-25 14:48:03
     */
    public static String encrypt(String password, String appSecret, String data) {
        return encrypt(password, appSecret, data, CHARSET);
    }

    /**
     * 3DES加密字符串--base64加密
     *
     * @param password 解密密码，长度不能够小于8位
     * @param data     待加密字符串
     * @return {@link String } 加密后内容
     * @author yuhh
     * @date 2023-05-25 14:48:07
     */
    public static String encrypt(String password, String data) {
        return encrypt(password, IV_PARAMETER, data, CHARSET);
    }

    /**
     * 3DES加密字符串--base64加密
     *
     * @param password 解密密码，长度不能够小于8位
     * @param data     待加密字符串
     * @param charset  编码
     * @return {@link String } 加密后内容
     * @author yuhh
     * @date 2023-05-25 14:48:14
     */
    public static String encrypt(String password, String data, Charset charset) {
        return encrypt(password, IV_PARAMETER, data, charset);
    }

    /**
     * 3DES加密字符串--base64加密
     *
     * @param password  解密密码，长度不能够小于8位
     * @param appSecret 偏移变量
     * @param data      待加密字符串
     * @param charset   编码
     * @return {@link String } 加密后内容
     * @author yuhh
     * @date 2023-05-25 14:48:22
     */
    public static String encrypt(String password, String appSecret, String data, Charset charset) {
        if (checkParameters(password, data)){
            return null;
        }
        try {
            byte[] bytes = handleEncrypt(password, appSecret, data, charset);

            return new String(Base64Util.encode(bytes));

        } catch (Exception e) {
            logger.error("DES加密字符串--base64加密，出现异常", e);
            return data;
        }
    }

    /**
     * 3DES解密字符串--base64加密
     *
     * @param password  解密密码，长度不能够小于8位
     * @param appSecret 偏移变量
     * @param data      待解密字符串
     * @return {@link String } 解密后内容
     * @author yuhh
     * @date 2023-05-25 14:48:34
     */
    public static String decrypt(String password, String appSecret, String data) {
        return decrypt(password, appSecret, data, CHARSET);
    }

    /**
     * 3DES解密字符串--base64加密
     *
     * @param password 解密密码，长度不能够小于8位
     * @param data     待解密字符串
     * @return {@link String } 解密后内容
     * @author yuhh
     * @date 2023-05-25 14:48:44
     */
    public static String decrypt(String password, String data) {
        return decrypt(password, IV_PARAMETER, data, CHARSET);
    }

    /**
     * 3DES解密字符串--base64加密
     *
     * @param password 解密密码，长度不能够小于8位
     * @param data     待解密字符串
     * @param charset  编码
     * @return {@link String } 解密后内容
     * @author yuhh
     * @date 2023-05-25 14:48:47
     */
    public static String decrypt(String password, String data, Charset charset) {
        return decrypt(password, IV_PARAMETER, data, charset);
    }

    /**
     * 3DES解密字符串--base64加密
     *
     * @param password  解密密码，长度不能够小于8位
     * @param appSecret 偏移变量
     * @param data      待解密字符串
     * @param charset   编码
     * @return {@link String } 解密后内容
     * @author yuhh
     * @date 2023-05-25 14:48:51
     */
    public static String decrypt(String password, String appSecret, String data, Charset charset) {
        if (checkParameters(password, data)){
            return null;
        }

        try {
            Key secretKey = generateKey(password);
            Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
            if (ObjectUtils.isEmpty(appSecret)){
                cipher.init(Cipher.DECRYPT_MODE, secretKey);
                return new String(cipher.doFinal(Base64Util.decode(data)), charset);
            }
            IvParameterSpec iv = new IvParameterSpec(appSecret.getBytes(charset));
            cipher.init(Cipher.DECRYPT_MODE, secretKey, iv);
            return new String(cipher.doFinal(Base64Util.decode(data)), charset);
        } catch (Exception e) {
            logger.error("DES解密字符串--base64加密，出现异常", e);
            return null;
        }
    }

    /**
     * 执行加密
     *
     * @param password  秘钥
     * @param appSecret 偏移量
     * @param data      需要加密的内容
     * @param charset   编码
     * @return {@link byte[] } 加密后的内容
     * @throws Exception 异常
     * @author yuhh
     * @date 2023-05-25 14:48:57
     */
    private static byte[] handleEncrypt(String password, String appSecret, String data, Charset charset) throws Exception {
        Key secretKey = generateKey(password);
        Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
        if (ObjectUtils.isEmpty(appSecret)){
            cipher.init(Cipher.ENCRYPT_MODE, secretKey);
            return cipher.doFinal(data.getBytes(charset));
        }
        IvParameterSpec iv = new IvParameterSpec(appSecret.getBytes(charset));
        cipher.init(Cipher.ENCRYPT_MODE, secretKey, iv);
        return cipher.doFinal(data.getBytes(charset));
    }

    /**
     * 校验参数
     *
     * @param password 秘钥
     * @param data     数据
     * @return boolean 是否校验通过，true：不通过；false：通过
     * @author yuhh
     * @date 2023-05-25 14:49:04
     */
    private static boolean checkParameters(String password, String data){
        if (password== null || password.length() < KEY_MIN_LENGTH) {
            throw new RuntimeException("解密失败，key不能小于8位");
        }
        return data == null;
    }

    /**
     * 生成key
     *
     * @param password 秘钥
     * @return {@link Key }
     * @throws Exception 异常
     * @author yuhh
     * @date 2023-05-25 14:49:09
     */
    private static Key generateKey(String password) throws Exception {
        DESedeKeySpec dks = new DESedeKeySpec(password.getBytes(CHARSET));
        SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(ALGORITHM);
        return keyFactory.generateSecret(dks);
    }

    public static void main(String[] args) {
        String c = "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?><In><Head><FTranCode>BJ01</FTranCode><InstID>nbgd" +
                "</InstID><TranDateTime>20210512045529</TranDateTime><BankNum>001922986518</BankNum><AnsCode" +
                "></AnsCode></Head><Body><billKey>124680</billKey><filed1></filed1><filed2></filed2><filed3></filed3><filed4></filed4><beginNum>1</beginNum><queryNum>1</queryNum></Body></In>";
        String key = "iabcotuvdejknpfwgqrsxhlm";
        System.out.println(TripleDesUtil.encrypt(key, c, CharsetUtil.CHARSET_GBK));
        System.out.println();
        String d = "PSNxeYk4yYm4uHKqhMduN5rZALIW/MIFa/pAhtBPinpIQbKCUyzHc5+WaGaWY099XoM2CLg/+EL/jY2VZ924Fsn+bGO/5SEE/42NlWfduBZmeKyUR7c7oovFF8PpIxdkZTLUBYuMIC51fxStjvVT/b+iu/39ufYEUaNxd5MWAhCqcgJfGR8xtinyDXTMt4XZkDVfwcmxWe3dmIPjps78GDOC/RXstmG+u6pfZGg+hGYRzt/i98xjrtznPInea8xv3LcZTGtzWEVLnlLQEi1S74V5SQiQH/n3H0jEpPq7AX4tNQRGIAyexsUewjIR2/hr50LMB3h51IiMFuwvXLXNqIkfij8CmwzoaP+b4PEZsAZe/ieONz4wQcUPfwL8+ih9/uHLx77QUdi7vxePZgnRKGWEM0Mqyuh4H/pM/JqyZL+lzXZae+0BlveYyH7fYw0/CzIkMaOWyNKYtujV/iThtG+FiWfwwo2tu+Qxbh7PEtY=";
        System.out.println(TripleDesUtil.decrypt(key, d, CharsetUtil.CHARSET_GBK));
    }

    private TripleDesUtil(){

    }
}